<template>
    <div class="demo-input-size">
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
            <el-form-item label="原密码" prop="oldpass">
                <el-input v-model="ruleForm.oldpass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" prop="pass">
                <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
                <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'

const ruleFormRef = ref<FormInstance>()


// 设置表单验证规则
const validateoldPass = (rule: object, value: string, callback: any) => {
    if (value === '') {
        callback(new Error('请输入原密码'))
    } else {
        callback()
    }
}

const validatePass = (rule: object, value: string, callback: any) => {
    if (value === '') {
        callback(new Error('请输入新密码'))
    } else {
        callback()
    }
}

const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入新密码'))
    } else if (value !== ruleForm.pass) {
        callback(new Error("密码不匹配"))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    oldpass: '',
    pass: '',
    checkPass: ''
})

const rules = reactive({
    oldpass: [{ validator: validateoldPass, trigger: 'blur' }],
    pass: [{ validator: validatePass, trigger: 'blur' }],
    checkPass: [{ validator: validatePass2, trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>
  
<style>
.demo-input-size {
  width: 80%;
  box-sizing: border-box;
  padding-left: 20%;
}</style>